package com.globallogic.qdumper;

import java.io.StringWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.util.Date;
import java.util.List;

import com.globallogic.qdumper.bean.QueryItem;
import com.globallogic.qdumper.jdbc.OdbcQueryHelper;
import com.globallogic.qdumper.xml.XmlHelper;


public class QueryDumperService
{

    private String dsnName;
    private String user;
    private String password;

    public void setDsnName(String dsnName)
    {
        this.dsnName = dsnName;
    }

    public String getUser()
    {
        return user;
    }

    public void setUser(String user)
    {
        this.user = user;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public String getDsnName()
    {
        return dsnName;
    }

    private OdbcQueryHelper odbcQueryHelper;

    public QueryDumperService()
    {
        odbcQueryHelper = new OdbcQueryHelper();
    }

    public void startSqlExecution(List<QueryItem> queryItems) throws Exception
    {
        odbcQueryHelper.connect(dsnName, user, password);

        try
        {
            for ( QueryItem queryItem : queryItems )
            {
                System.out.println("Running sql query from file: " + queryItem.getQueryFileName());
                String sqlQuery = queryItem.getQueryText();

                long startTime = new Date().getTime();
                ResultSet results = odbcQueryHelper.executeQuery(sqlQuery);
                long endTime = new Date().getTime();

                Writer writer = new StringWriter();
                XmlHelper.resultSetToXml(results, writer);

                queryItem.setResultText(writer.toString());
                queryItem.setExecutedTime(endTime - startTime);
            }
        }
        finally
        {
            odbcQueryHelper.disconnect();
        }

    }
}
